import { App, ref, UnwrapRef } from "vue";
import type { ModuleInterface, ModuleConfig, SendCmd } from "./types";
import AddTask from "./components/indev.vue";
import type { Response } from "./types";
import { SEND_CREATE_TASK_CMD_KEY, GET_CREATE_TASK_DATA_KEY } from "./types"; // 导入字符串Key

const config: ModuleConfig = {
  id: "CreateTask",
  name: "任务模块",
  version: "1.0.0",
  description: "任务列表查询"
};

export class TaskModule<
  EventData extends object = object, // 约束为对象，解决 Object.assign 问题
  Payload = any, 
  Return = Response<any> // 泛型 Response，解决问题2&5
> implements ModuleInterface<EventData, Payload, Return> {

  config = config;
  private eventData: UnwrapRef<EventData>;
  private sendCmd: SendCmd<Payload, Return>;

  constructor(initialData: EventData, sendCmd: SendCmd<Payload, Return>) {
    this.eventData = ref(initialData) as unknown as UnwrapRef<EventData>;
    this.sendCmd = sendCmd;
  }

  sendCommand(cmd: string, payload?: Payload): Return | Promise<Return> {
    console.log("发送指令：", cmd, payload);
    return this.sendCmd(this.config.id, cmd, payload);
  }

  install(app: App): void {
    app.component("AddTask", AddTask);

    app.provide(GET_CREATE_TASK_DATA_KEY, () => this.getEventData());

    app.provide(SEND_CREATE_TASK_CMD_KEY, (cmd: string, payload?: Payload): Return | Promise<Return> => {
      console.log("内部转发指令：", cmd, payload);
      return this.sendCommand(cmd, payload);
    });
  }

  getEventData(): EventData { 
    return this.eventData as EventData; 
  }

  updateEventData(data: Partial<EventData>): void { 
    Object.assign(this.eventData as Object, data); 
  }

  async startup(): Promise<void> { 
    console.log("校准模块初始化完成"); 
  }
}

export const createTaskModule = <
  EventData extends object = object,
  Payload = any, 
  Return = Response<any>
>(
  initialData: EventData,
  sendCmd: SendCmd<Payload, Return>
): ModuleInterface<EventData, Payload, Return> => {
  return new TaskModule<EventData, Payload, Return>(initialData, sendCmd);
};

export default createTaskModule;